<?php

/*
 * Copyright (C) 2009 - 2011 Pham Cong Dinh
 *
 * This file is part of Spica.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 3 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

/**
 * <p>Set of methods to support input filtering.</p>
 *
 * namespace spica\core\utils\FilterUtils
 *
 * @category   spica
 * @package    core
 * @subpackage utils
 * @author     Pham Cong Dinh <pcdinh at phpvietnam dot net>
 * @since      Version 0.2
 * @since      March 22, 2009
 * @copyright  Pham Cong Dinh (http://www.phpvietnam.net)
 * @license    http://www.gnu.org/licenses/lgpl-3.0.txt
 * @version    $Id: FilterUtils.php 1869 2011-01-07 18:55:25Z pcdinh $
 */
class SpicaFilterUtils
{
    /**
     * Returns only the alphabetic characters in value.
     *
     * @param  mixed $value
     * @return mixed
     */
    public static function getAlpha($value)
    {
        return preg_replace('/[^[:alpha:]]/', '', $value);
    }

    /**
     * Returns only the alphabetic characters and digits in value.
     *
     * @param  mixed $value
     * @return mixed
     */
    public static function getAlnum($value)
    {
        return preg_replace('/[^[:alnum:]]/', '', $value);
    }

    /**
     * Returns only the digits in value. This differs from getInt().
     *
     * @param  mixed $value
     * @return mixed
     */
    public static function getDigits($value)
    {
        return preg_replace('/[^\d]/', '', $value);
    }

    /**
     * Returns dirname(value).
     *
     * @param  mixed $value
     * @return mixed
     */
    public static function getDir($value)
    {
        return dirname($value);
    }

    /**
     * Returns (int) value.
     *
     * @param  mixed $value
     * @return int
     */
    public static function getInt($value)
    {
        return (int) $value;
    }

    /**
     * Returns first $length characters of value.
     *
     * @param  mixed $value
     * @param  int $length
     * @return mixed
     */
    public static function getLength($value, $length = NULL)
    {
        return substr($value, 0, $length);
    }

    /**
     * Returns realpath(value).
     *
     * @param  mixed $value
     * @return mixed
     */
    public static function getPath($value)
    {
        return realpath($value);
    }

    /**
     * Returns value with all tags removed.
     *
     * @param  string $value
     * @return string
     */
    public static function noTags($value)
    {
        return strip_tags($value);
    }

    /**
     * Returns basename(value).
     *
     * @param  mixed $value
     * @return mixed
     */
    public static function noPath($value)
    {
        return basename($value);
    }

    /**
     * Converts a phrase to a URL-safe title.
     *
     * @param  string $title phrase to convert
     * @param  int    $maxlen max string length return
     * @param  string $separator word separator (- or _)
     * @return string
     */
    public static function titleUrl($title, $maxlen = 150, $separator = '-')
    {
        $separator = ($separator === '-') ? '-' : '_';
        // Replace accented characters by their unaccented equivalents
        $title = self::transliterateToAscii($title, $separator);
        // Remove all characters that are not the separator, a-z, 0-9, or whitespace
        $title = preg_replace('/[^'.$separator.'a-z0-9\s]+/', '', strtolower($title));
        // Replace all separator characters and whitespace by a single separator
        $title = preg_replace('/['.$separator.'\s]+/', $separator, $title);
        // Trim separators from the beginning and end
        return trim(substr($title, 0, $maxlen), $separator);
    }

    /**
     * Formats a string to be alphanumeric name safe.
     *
     * Ported from my PONE framework.
     *
     * @param  string $string The string
     * @param  string $replaceNonAscii The non-ASCII characters will be replaced by this character
     * @return string Alphanumeric string
     */
    public static function transliterateToAscii($string, $replaceNonAscii = '_')
    {
        // Replace other special chars
        $specialChars = array(
          'sharp'   => '#',
          'dot'     => '.',
          'plus'    => '+',
          'and'     => '&',
          'percent' => '%',
          'dollar'  => '$',
          'equals'  => '=',
        );

        while (list($replacement, $char) = each($specialChars))
        {
            $string = str_replace($char, '-' . $replacement . '-', $string);
        }

        // Fix german special chars
        $string  = preg_replace('/[äÄ]/', 'ae', $string);
        $string  = preg_replace('/[üÜ]/', 'ue', $string);
        $string  = preg_replace('/[öÖ]/', 'oe', $string);
        $string  = preg_replace('/[ß]/', 'ss', $string);

        $noalpha = 'ÁÉÍÓÚÝáéíóúýÂÊÎÔÛâêîôûÀÈÌÒÙÛûàèìòùÄËÏÖØÜäëïöüÿÃãÕõÅåÑñÇçÅå@°ºªăĂắẮặẶằẰẳẲấẤậẬầẦẩẨốỐồỒộỘổỔếẾềỀệỆểỂưƯừỪứỨựỰửỬịỊỉỈọỌỏỎẹEẻẺ';
        $alpha   = 'AEIOUYaeiouyAEIOUaeiouAEIOUUuaeiouAEIOoUaeiouyAaOoAaNnCcAaaooaaAaAaAaAaAaAaAaAaAoOoOoOoOeEeEeEeEuUuUuUuUuUiIiIoOoOeẸeE';
        $string  = strtr($string, $noalpha, $alpha);
        // not permitted chars are replaced with "_"
        return preg_replace('/[^a-zA-Z0-9,._\+\()\-]/', $replaceNonAscii, $string);
    }

    /**
     * Converts more-than-white-space substrings into a single white space.
     *
     * @param  string $string
     * @return string
     */
    public static function collapseWhiteSpace($string)
    {
        return preg_replace('/\s+/', ' ', $string);
    }

    /**
     * Removes null only values from an aray.
     *
     * @param array $array
     */
    public static function noNull($array)
    {
        return array_filter($array, 'strlen');
    }

    /**
     * Removes null, empty, false values from an aray.
     *
     * @param array $array
     */
    public static function noFalse($array)
    {
        return array_filter($array);
    }
}

?>